package wge

import(
	"fmt"
)

// 路由器

type Router interface {
	/** 添加路由信息 */
	AddMethod(string, ...Handler)
}

// 路由分发器
func (r *router)Handle(c *Context) Stringer {
	methods, ok := r.group[c.Req.URL.Path[1:]]
	if ok {
		for _, m := range methods {
			ret := m(c)
			if ret != nil {
				body := ret.ToString()
				if body == "" {
					fmt.Fprint(c.w, Err(error_returnparsewrong, ""))
				} else {
					fmt.Fprint(c.w, body)
				}
				return nil
			} else if c.status != 0 {
				return nil
			}
		}
		// 在没有返回值的情况下，默认返回成功
		fmt.Fprint(c.w, Err(error_noerror, ""))
	} else {	// 找不到该方法
		msg := fmt.Sprintf("method '%s' not exist", c.Req.URL.Path[1:])
		logger.Println(msg)
		fmt.Fprint(c.w, Err(error_methodnofind, msg))
	}
	
	return nil
}

// 路由响应器
type route map[string][]Handler

type router struct {
	group	route
}

func createRouter() *router {
	return &router{route{}}
}

func (r *router)AddMethod(name string, h ...Handler) {
	_, ok := r.group[name]
	if !ok {
		r.group[name] = h
	} else {
		fmt.Printf("Name %s's route had added!\n", name)
	}
}